package edu.uoc.vmerinom.tfc.backup;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.persistence.EntityManager;

import edu.uoc.vmerinom.tfc.domain.Reunion;

public class Reuniones {
	@SuppressWarnings("unchecked")
	public static String backup(EntityManager entityManager) {
		StringBuffer backup = new StringBuffer();
		List<Reunion> reuniones = entityManager.createQuery("from Reunion order by id").getResultList();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (Reunion reunion : reuniones) {
			//id, creado, modificado, baja, fecha, orden, acuerdos, observaciones
			StringBuffer insert = new StringBuffer();
			insert.append("insert into reuniones (id, creado, modificado, baja, fecha, lugar, orden, acuerdos, observaciones, email) ");
			insert.append("values (");
			insert.append(reunion.getId());
			insert.append(", current_timestamp, current_timestamp, ");
			if (reunion.getBaja() != null) {
				insert.append("'");
				insert.append(sdf.format(reunion.getBaja()));
				insert.append("', ");
			} else {
				insert.append("null, ");
			}
			insert.append("'");
			insert.append(sdf.format(reunion.getFecha()));
			insert.append("', ");
			if (reunion.getLugar() != null) {
				insert.append("'");
				insert.append(reunion.getLugar());
				insert.append("', '");
			} else {
				insert.append("null, '");
			}
			insert.append(prepare(reunion.getOrden()));
			insert.append("', ");
			if (reunion.getAcuerdos() != null) {
				insert.append("'");
				insert.append(prepare(reunion.getAcuerdos()));
				insert.append("', ");
			} else {
				insert.append("null, ");
			}
			if (reunion.getObservaciones() != null) {
				insert.append("'");
				insert.append(prepare(reunion.getObservaciones()));
				insert.append("', ");
			} else {
				insert.append("null, ");
			}
			insert.append(reunion.isEmail());
			insert.append(");\n");
			backup.append(insert);
		}
		return backup.toString();
	}

	private static String prepare(String string) {
		StringBuffer changed = new StringBuffer();
		char[] array = string.toCharArray();
		for (char c : array) {
			if (c == '\n') {
				changed.append("\\n");
			} else {
				changed.append(c);
			}
		}
		return changed.toString();
	}
}
